package com.sysd.mail.send;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

/**
 * project: mail
 *
 * @author bsh
 * @description smtpClient
 * @dataTime 2023/10/26 10:17
 * @company 丽水信阳软件科技有限公司
 */
public class SmtpClient {
    private final String host;
    private final Integer port;
    private final Bootstrap bootstrap;

    public SmtpClient(String host, Integer port) {
        this.host = host;
        this.port = port;
        this.bootstrap = setup();
    }

    private Bootstrap setup() {
        EventLoopGroup group = new NioEventLoopGroup();
        return new Bootstrap()
                .group(group)
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new MessageHandler());
                    }
                });
    }

    public void run() {
        try {
            bootstrap.connect(host, port).sync().channel().closeFuture().sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
